package com.example.jean.lpws;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Context;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jean on 25/10/2014.
 */
public class GcmIntentService extends IntentService {

    WifiManager mainWifiObj;
    ListView list;
    String wifis[];

    // Informacoes do roteador/AP
    String[] BSSID; // basic service set identifier - nome da conexao
    String[] SSID; // service set identifier - identificador unico da conexao
    int[] RSSI; // received signal strength indicator - potencia do sinal (-87 a -32)

    public static final int NOTIFICATION_ID = 1;
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_USER_NAME = "nome";
    static final String TAG = "GCMDemo";
    private Handler handler;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    String mes;
    String regId,sender;
    String nome;
    String action;
    String result;

    public GcmIntentService() {
        super("GcmIntentService");
    }
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        handler = new Handler();
        final SharedPreferences prefs = getGCMPreferences(getApplicationContext());
        regId = prefs.getString(PROPERTY_REG_ID, "");
        nome = prefs.getString(PROPERTY_USER_NAME, "");


        mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    }
    private SharedPreferences getGCMPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.
        return getSharedPreferences(Main.class.getSimpleName(),
                        Context.MODE_PRIVATE);
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM
             * will be extended in the future with new message types, just ignore
             * any message types you're not interested in, or that you don't
             * recognize.
             */
            if (GoogleCloudMessaging.
                    MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification("Deleted messages on server: " +
                        extras.toString());
                // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
                /*for (int i=0; i<5; i++) {
                    Log.i(TAG, "Working... " + (i+1)
                            + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());*/
                // Post notification of received message.
                sendNotification("Received: " + extras.getString("message"));
                mes = extras.getString("title");
                action = extras.getString("action");
                sender = extras.getString("sender");
                result = extras.getString("result");

                showToast();
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    // Put the message into a notification and post it.
    // This is just one simple example of what you might choose to do with
    // a GCM message.
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, Main.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_stat_gcm)
                        .setContentTitle("GCM Notification")
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(msg))
                        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
    public void showToast(){
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(),mes , Toast.LENGTH_LONG).show();
                if(action.compareTo("doScan")==0) {
                    startWifiScan();
                    sendPost();
                }
                if(action.compareTo("showResult")==0){
                        Intent intent = new Intent("com.sociesc.MSG_RECEIVED");
                        intent.putExtra("result", result);
                        sendBroadcast(intent);
                }
            }
        });

    }
    private void startWifiScan(){
        //wifiReceiver = new WifiScanReceiver();
        mainWifiObj.startScan();

        List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
        wifis = new String[wifiScanList.size()];

        RSSI = new int[wifiScanList.size()];
        BSSID = new String[wifiScanList.size()];
        SSID = new String[wifiScanList.size()];

        for (int i = 0; i < wifiScanList.size(); i++) {
            wifis[i] = ((wifiScanList.get(i)).toString());
            BSSID[i] = (wifiScanList.get(i).BSSID);
            SSID[i] = (wifiScanList.get(i).SSID);
            RSSI[i] = wifiScanList.get(i).level;
            Log.i("WIFI LIST",wifis[i]);
        }
    }
    private void sendPost(){
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.1.5/lpws/receiver");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(wifis.length+3);
            nameValuePairs.add(new BasicNameValuePair("api_client_id", regId)); // quem está sendo localizado
            nameValuePairs.add(new BasicNameValuePair("sender", sender)); // quem está requisitando
            nameValuePairs.add(new BasicNameValuePair("length",String.valueOf(wifis.length)));
            for(int i=0;i<wifis.length;i++){
                nameValuePairs.add(new BasicNameValuePair("WIFI_"+i, SSID[i]+"|"+BSSID[i]+"|"+String.valueOf(RSSI[i])));
                Log.i(TAG,"WIFI_"+i+"|"+SSID[i]+"|"+BSSID[i]+"|"+String.valueOf(RSSI[i]));
            }
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            msg = "Error :" + e.getMessage();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            msg = "Error :" + e.getMessage();
        }
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
               Log.i(TAG,msg);
            }
        }.execute(null, null, null);
    }

}
